using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace Theodorus
{
	public static class ValidationExtensions
	{
		public static bool ValidateAllBindings(this DependencyObject parent)
		{
			var valid = true;
			var localValues = parent.GetLocalValueEnumerator();
			while (localValues.MoveNext())
			{
				var entry = localValues.Current;
				if (!BindingOperations.IsDataBound(parent, entry.Property)) continue;
				var binding = BindingOperations.GetBinding(parent, entry.Property);
				if (binding == null) continue;
				foreach (var rule in binding.ValidationRules)
				{
					var result = rule.Validate(parent.GetValue(entry.Property), null);
					if (result.IsValid) continue;
					var expr = BindingOperations.GetBindingExpression(parent, entry.Property);
					if (expr == null) continue;
					Validation.MarkInvalid(expr, new ValidationError(rule, expr, result.ErrorContent, null));
					valid = false;
				}
			}

			for(var i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
			{
				var child = VisualTreeHelper.GetChild(parent, i);
				if (!child.ValidateAllBindings())
				{
					valid = false;
				}
			}

			return valid;
		}
	}
}